package com.example.active.sf;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2020/9/17 8:39
 */
public class ProducerConsumer
{
    static ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://192.168.0.118:61616");

    public static void main(String[] args)
    {
        try
        {
            System.out.println("消费者1");
            Connection connection = factory.createConnection();
            connection.setClientID("z3");

            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            //创建目的地
            Topic topic = session.createTopic("topic01");
            //创建消费者
//            MessageConsumer consumer = session.createConsumer(topic);
            TopicSubscriber subscriber = session.createDurableSubscriber(topic, "remark");
            connection.start();
            Message receive = subscriber.receive();
            while (null !=receive){
                TextMessage message = (TextMessage) receive;
                System.out.println("****收到的持久化topic："+message.getText());
                receive = subscriber.receive();
            }

//            for(;;){
//                //生产者产生的消息就是TextMessage
//                TextMessage receive = (TextMessage) consumer.receive();
//                if(null != receive){
//                    System.out.println("接收消息："+receive.getText());
//                }else {
//                    break;
//                }
//            }

            //设置监听器
//            consumer.setMessageListener(message -> {
//                if(message instanceof TextMessage &&null !=message){
//                    try
//                    {
//                        TextMessage textMessage = ((TextMessage) message);
//                        System.out.println("接收消息："+textMessage.getText());
//                    } catch (JMSException e)
//                    {
//                        e.printStackTrace();
//                    }
//                }
//            });
//            System.in.read();//保证控制台不灭
//            consumer.close();
            session.close();
            connection.close();
        } catch (JMSException e)
        {
            e.printStackTrace();
        }
    }
}
